package com.michael.study.component.fragment

import android.content.res.Configuration
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.michael.study.component.R
import kotlinx.android.synthetic.main.activity_fragment.*

class FragmentActivity : AppCompatActivity(), View.OnClickListener {

    private lateinit var blankFragment: BlankFragment
    private var fragmentA = FragmentA.newInstance()
    private var fragmentB = FragmentB.newInstance()
    private var fragmentC = FragmentC.newInstance()
    private var fragmentD = FragmentD.newInstance()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_fragment)

        val fragmentTransaction = supportFragmentManager.beginTransaction()

        if (savedInstanceState == null) {
            blankFragment = BlankFragment.newInstance()
            fragmentTransaction
                .add(R.id.container, blankFragment, "blank")
        } else {
            blankFragment = supportFragmentManager.findFragmentByTag("blank") as BlankFragment
        }
        fragmentTransaction.commit()

        btn_replace.setOnClickListener(this)
        btn_attach.setOnClickListener(this)
        btn_detach.setOnClickListener(this)
        btn_hide.setOnClickListener(this)
        btn_show.setOnClickListener(this)


    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        if (isFinishing || supportFragmentManager == null || supportFragmentManager.isStateSaved) {
            return
        }
        supportFragmentManager.beginTransaction()
            .replace(R.id.container, fragmentB, "B")
            .commit()
    }


    override fun onClick(v: View?) {
        when (v?.id) {

            R.id.btn_replace -> {
                supportFragmentManager.beginTransaction()
                    .replace(R.id.container, fragmentB, "B")
                    .commit()
            }

            R.id.btn_attach -> {
                supportFragmentManager.beginTransaction()
                    .attach(blankFragment)
                    .commit()
            }

            R.id.btn_detach -> {
                supportFragmentManager.beginTransaction()
                    .detach(blankFragment)
                    .commit()
            }

            R.id.btn_show -> {
                supportFragmentManager.beginTransaction()
                    .show(blankFragment)
                    .commit()
            }

            R.id.btn_hide -> {
                supportFragmentManager.beginTransaction()
                    .hide(blankFragment)
                    .commit()
            }
        }
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        Log.d("lgq", "onConfigurationChanged: ")
    }
}